/* eslint-disable no-unused-vars */
import axios from 'axios';
import { _tiper, LOAD } from '@/base/util/ui';
import { api as $api } from '@/common/config/api.js';
import { _tiper as $tip } from '@/base/util/ui';

const request = {
  temp: {
    loadingCount: 0, // 加载计数器
    loadingInstance: null, // 加载实例
    userInfoTemp: null // 用户信息缓存
  }
};

/**
 * 加载框事件
 * @param {boolean} flag  开关标志
 * @param {Object} options [加载框参数]
 */
function loading(flag, options) {
  options = options || {};
  const msg = options.msg ? options.msg : null;
  // let target = options.el ? options.el.replace(/#|\./,""): "";
  const target = options.el ? options.el : '';
  const loadingCount = request.temp['loadingCount' + target];
  const loadingInstance = request.temp['loadingInstance' + target];
  if (isNaN(loadingCount)) {
    request.temp['loadingCount' + target] = 0;
  }
  /* console.log(target);
  console.log(loadingCount);
  console.log(loadingInstance); */

  if (flag) {
    if (++request.temp['loadingCount' + target] === 1) {
      request.temp['loadingInstance' + target] = LOAD(msg, target);
    }
  } else {
    if (--request.temp['loadingCount' + target] === 0) {
      if (loadingInstance) {
        request.temp['loadingInstance' + target].close();
        request.temp['loadingInstance' + target] = null;
      }
    }
  }
}

/**
 * 提交表单信息
 * @param {*} method 方法名
 * @param {*} param 参数
 * @param {*} options 选项
 */
export function postFormData(method, param, options) {
  axios.defaults.timeout = 120000; // 请求超时时间
  return new Promise((resolve, reject) => {
    loading(true, options);
    axios
      .post(method, param, {
        'Content-Type': 'multipart/form-data'
      })
      .then(res => {
        resolve(res.data.ROOT.BODY);
        loading(false, options);
      })
      .catch(err => {
        reject(err.data);
        loading(false, options);
      });
  });
}

/**
 * 附件上传
 * @param {*} formData
 * @returns
 */
export function uploadFile(formData) {
  return new Promise((resolve, reject) => {
    postFormData($api.user.upload2, formData).then(res => {
      if (res.RETURN_CODE === '0') {
        const fileObj = res.OUT_DATA
        resolve(fileObj)
      } else {
        $tip.error(res.RETURN_MSG)
        reject(res)
      }
    }).catch(res => {
      $tip.error('上传附件发生异常！')
      reject(res)
    })
  });
}
